//
//  HNSH_AgentAddressView.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/6/30.
//

#import "HNSH_AgentAddressView.h"
#import "HNSH_AgentAddressViewCell.h"

@interface HNSH_AgentAddressView ()<UIScrollViewDelegate,UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UIScrollView *titleScrollView;
@property(nonatomic,strong)UIScrollView *contentScrollView;
@property(nonatomic,strong)UIButton *radioBtn;
@property(nonatomic,strong)NSMutableArray *titleBtns;
@property(nonatomic,strong)NSMutableArray *titleMarr;
@property(nonatomic,strong)NSMutableArray *tableViewMarr;
@property(nonatomic,strong)UILabel *lineLabel;
@property(nonatomic,assign)BOOL isInitalize;
@property(nonatomic,assign)BOOL isclick; //判断是滚动还是点击
@property(nonatomic,strong)NSArray *provinceMarr;//省
@property(nonatomic,strong)NSArray *cityMarr;//市
@property(nonatomic,strong)NSArray *countyMarr;//县
@property(nonatomic,strong)NSArray *townMarr;//乡
@property(nonatomic,strong)NSArray *resultArr;//本地数组
@property (nonatomic, copy) NSString *PCCTID;
@property(nonatomic,assign)NSInteger scroolToRow; //确定在更改地址的时候能滚到对应的位置请求到下一级

@end

static NSString *HNSH_AgentAddressViewCellID = @"HNSH_AgentAddressViewCellID";

@implementation HNSH_AgentAddressView

-(NSMutableArray *)titleBtns
{
    if (_titleBtns == nil) {
        _titleBtns = [[NSMutableArray alloc]init];
    }
    return _titleBtns;
}
-(NSMutableArray *)titleMarr
{
    if (_titleMarr == nil) {
        _titleMarr = [[NSMutableArray alloc]init];
    }
    return _titleMarr;
}
-(NSMutableArray *)tableViewMarr
{
    if (_tableViewMarr == nil) {
        _tableViewMarr = [[NSMutableArray alloc]init];
    }
    return _tableViewMarr;
}
-(NSMutableArray *)titleIDMarr
{
    if (_titleIDMarr == nil) {
        _titleIDMarr = [[NSMutableArray alloc]init];
    }
    return _titleIDMarr;
}

-(UIView *)initAddressView{
    //初始化本地数据（如果是网络请求请注释掉-----
//    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"location" ofType:@"txt"];
//    NSString *string = [[NSString alloc] initWithContentsOfFile:imagePath encoding:NSUTF8StringEncoding error:nil];
//    NSData * resData = [[NSData alloc]initWithData:[string dataUsingEncoding:NSUTF8StringEncoding]];
//    _resultArr = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
    //------到这里
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    self.hidden = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelBtnAndcancelBtnClick)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    //设置添加地址的View
    self.addAddressView = [[UIView alloc]init];
    self.addAddressView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, _defaultHeight);
    self.addAddressView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.addAddressView];
    UILabel * titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(40, 10, kScreenWidth - 80, 30)];
    titleLabel.text = _title;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor colorWithHexString:@"#333333"];
    titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [self.addAddressView addSubview:titleLabel];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame =CGRectMake(10, 10, 40, 30);
    cancelBtn.tag = 1;
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [cancelBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnAndcancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.addAddressView addSubview:cancelBtn];
    
    UIButton *okBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    okBtn.frame =CGRectMake(CGRectGetMaxX(self.addAddressView.frame) - 50, 10, 40, 30);
    okBtn.tag = 1;
    [okBtn setTitle:@"确定" forState:UIControlStateNormal];
    okBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [okBtn setTitleColor:[UIColor appGreenColor] forState:UIControlStateNormal];
    [okBtn addTarget:self action:@selector(tapBtnAndcancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.addAddressView addSubview:okBtn];
    
    [self addTableViewAndTitle:0];
    //1.添加标题滚动视图
    [self setupTitleScrollView];
    //2.添加内容滚动视图
    [self setupContentScrollView];
    [self setupAllTitle:0];
    return self;
}
-(void)addAnimate{
    self.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
        self.addAddressView.frame = CGRectMake(0, kScreenHeight - self.defaultHeight, kScreenWidth, self.defaultHeight);
    }];
}
- (void)cancelBtnAndcancelBtnClick {
    self.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
         self.addAddressView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 200);
    } completion:^(BOOL finished) {
        self.hidden = YES;
    }];
}
-(void)tapBtnAndcancelBtnClick{
    self.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
         self.addAddressView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 200);
    } completion:^(BOOL finished) {
        self.hidden = YES;
        NSMutableString * titleAddress = [[NSMutableString alloc]init];
        NSMutableString * titleID = [[NSMutableString alloc]init];
        NSInteger  count = 0;
        NSString * str = self.titleMarr[self.titleMarr.count - 1];
        if ([str isEqualToString:@"请选择"]) {
            count = self.titleMarr.count - 1;
        }
        else{
            count = self.titleMarr.count;
        }
        for (int i = 0; i < count ; i++) {
            if (i == 0) {
                [titleAddress appendString:[[NSString alloc]initWithFormat:@"%@",self.titleMarr[i]]];
                [titleID appendString:[[NSString alloc]initWithFormat:@"%@",self.titleIDMarr[i]]];
            } else {
                [titleAddress appendString:[[NSString alloc]initWithFormat:@"/%@",self.titleMarr[i]]];
                [titleID appendString:[[NSString alloc]initWithFormat:@"/%@",self.titleIDMarr[i]]];
            }
        }
        [self.delegate cancelBtnClick:titleAddress titleID:titleID];
    }];
}
-(void)setupTitleScrollView{
    //TitleScrollView和分割线
    self.titleScrollView = [[UIScrollView alloc]init];
    self.titleScrollView.frame = CGRectMake(0, 50, kScreenWidth, _titleScrollViewH);
    [self.addAddressView addSubview:self.titleScrollView];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.titleScrollView.frame), kScreenWidth, 0.5)];
    lineView.backgroundColor = [UIColor grayColor];
    [self.addAddressView addSubview:(lineView)];
}
-(void)setupContentScrollView{
    //ContentScrollView
    CGFloat y  =  CGRectGetMaxY(self.titleScrollView.frame) + 1;
     self.contentScrollView = [[UIScrollView alloc]init];
    self.contentScrollView.frame = CGRectMake(0, y, kScreenWidth, self.defaultHeight - y);
    [self.addAddressView addSubview:self.contentScrollView];
    self.contentScrollView.delegate = self;
    self.contentScrollView.pagingEnabled = YES;
    self.contentScrollView.bounces = NO;
}
-(void)setupAllTitle:(NSInteger)selectId{
    for ( UIView * view in [self.titleScrollView subviews]) {
         [view removeFromSuperview];
    }
    [self.titleBtns removeAllObjects];
    CGFloat btnH = self.titleScrollViewH;
    _lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
    _lineLabel.backgroundColor = [UIColor appGreenColor];
    [self.titleScrollView addSubview:(_lineLabel)];
    CGFloat x = 10;
    for (int i = 0; i < self.titleMarr.count ; i++) {
        NSString   *title = self.titleMarr[i];
        CGFloat titlelenth = title.length * 15;
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [titleBtn setTitle:title forState:UIControlStateNormal];
        titleBtn.tag = i;
        [titleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
         [titleBtn setTitleColor:[UIColor appGreenColor] forState:UIControlStateSelected];
        titleBtn.selected = NO;
        titleBtn.frame = CGRectMake(x, 0, titlelenth, btnH);
        x  = titlelenth + 10 + x;
        [titleBtn.titleLabel setFont:[UIFont systemFontOfSize:13.0]];
        [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.titleBtns addObject:titleBtn];
        if (i == selectId) {
            [self titleBtnClick:titleBtn];
        }
        [self.titleScrollView addSubview:(titleBtn)];
        self.titleScrollView.contentSize =CGSizeMake(x, 0);
        self.titleScrollView.showsHorizontalScrollIndicator = NO;
        self.contentScrollView.contentSize = CGSizeMake(self.titleMarr.count * kScreenWidth, 0);
        self.contentScrollView.showsHorizontalScrollIndicator = NO;
    }
}
-(void)titleBtnClick:(UIButton *)titleBtn{
    self.radioBtn.selected = NO;
    titleBtn.selected = YES;
    [self setupOneTableView:titleBtn.tag];
    CGFloat x  = titleBtn.tag * kScreenWidth;
    self.lineLabel.frame = CGRectMake(CGRectGetMinX(titleBtn.frame), self.titleScrollViewH - 3,titleBtn.frame.size.width, 3);
    [UIView animateWithDuration:0.25 animations:^{
         self.contentScrollView.contentOffset = CGPointMake(x, 0);
    }];
    self.radioBtn = titleBtn;
    self.isclick = YES;
    }
-(void)setupOneTableView:(NSInteger)btnTag{
    UITableView  * contentView= self.tableViewMarr[btnTag];
    if  (btnTag == 0) {
        [self getAddressMessageDataAddressID:1 parentCode:@"1"];
    }
    if (contentView.superview != nil) {
        return;
    }
    CGFloat  x= btnTag * kScreenWidth;
    contentView.frame = CGRectMake(x, 0, kScreenWidth, self.contentScrollView.bounds.size.height);
    contentView.delegate = self;
    contentView.dataSource = self;
    [self.contentScrollView addSubview:(contentView)];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger leftI  = scrollView.contentOffset.x / kScreenWidth;
    if (scrollView.contentOffset.x / kScreenWidth != leftI){
        self.isclick = NO;
    }
    if (self.isclick == NO) {
        if (scrollView.contentOffset.x / kScreenWidth == leftI){
            UIButton * titleBtn  = self.titleBtns[leftI];
            [self titleBtnClick:titleBtn];
        }
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 0) {
        return self.provinceMarr.count;
    }
    else if (tableView.tag == 1) {
        return self.cityMarr.count;
    }
    else if (tableView.tag == 2){
        return self.countyMarr.count;
    }
    else if (tableView.tag == 3){
        return self.townMarr.count;
    }
    else{
        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HNSH_AgentAddressViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_AgentAddressViewCellID];
     if (tableView.tag == 0 && self.provinceMarr.count > indexPath.row) {
        DLAddressModel * provinceModel = self.provinceMarr[indexPath.row];
        cell.nameLabel.text = provinceModel.name;
        self.PCCTID = provinceModel.code;
    }
    else if (tableView.tag == 1  && self.cityMarr.count > indexPath.row) {
        DLAddressModel *cityModel = self.cityMarr[indexPath.row];
        cell.nameLabel.text= cityModel.name;
        self.PCCTID = cityModel.code;
    }
    else if (tableView.tag == 2 && self.countyMarr.count > indexPath.row){
        DLAddressModel * countyModel  = self.countyMarr[indexPath.row];
        cell.nameLabel.text = countyModel.name;
        self.PCCTID = countyModel.code;
    }
    else if (tableView.tag == 3 && self.townMarr.count > indexPath.row){
        DLAddressModel * townModel  = self.townMarr[indexPath.row];
        cell.nameLabel.text = townModel.name;
        self.PCCTID = townModel.code;
    }
    if (self.titleIDMarr.count > tableView.tag){
        NSString  *pcctId  =  self.titleIDMarr[tableView.tag];
        if ([self.PCCTID isEqualToString:pcctId]){
            [cell.nameLabel setTextColor:[UIColor appGreenColor]];
            [cell.imageIcon setHidden:false];
            if (self.isChangeAddress == true){
                [self tableView:tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
            }
        }
        else{
            [cell.nameLabel setTextColor:UIColor.grayColor];
            [cell.imageIcon setHidden:true];
        }
    }
    CGSize sizeNew = [cell.nameLabel.text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:13]}];
    // 重新设置frame
    cell.nameLabel.frame = CGRectMake(20, 0, sizeNew.width, 40);
    cell.imageIcon.frame = CGRectMake(20 + sizeNew.width + 5, 25/2, 15, 15);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isChangeAddress == false) {
        //先刷新当前选中的tableView
        UITableView * tableView1   = self.tableViewMarr[tableView.tag];
        [tableView1 reloadData];
    }
    if (tableView.tag == 0 || tableView.tag == 1 || tableView.tag == 2){
        if (tableView.tag == 0){
            DLAddressModel *provinceModel = self.provinceMarr[indexPath.row];
            NSString * provinceID = provinceModel.code;
            //1. 修改选中ID
            if (self.titleIDMarr.count > 0){
                [self.titleIDMarr replaceObjectAtIndex:tableView.tag withObject:provinceID];
            }
            else{
                [self.titleIDMarr addObject:provinceID];
            }
            //2.修改标题
              [self.titleMarr replaceObjectAtIndex:tableView.tag withObject:provinceModel.name];
            //请求网络 添加市区
            [self getAddressMessageDataAddressID:2 parentCode:provinceID];
        } else if (tableView.tag == 1){
            DLAddressModel * cityModel = self.cityMarr[indexPath.row];
            NSString * cityID = cityModel.code;
             [self.titleMarr replaceObjectAtIndex:tableView.tag withObject:cityModel.name];
            //1. 修改选中ID
            if (self.titleIDMarr.count > 1){
                [self.titleIDMarr replaceObjectAtIndex:tableView.tag withObject:cityID];
            }
            else{
                 [self.titleIDMarr addObject:cityID];
            }
            //网络请求，添加县城
            [self getAddressMessageDataAddressID:3 parentCode:cityID];
        } else if (tableView.tag == 2) {
            DLAddressModel * countyModel = self.countyMarr[indexPath.row];
            NSString * countyID = countyModel.code;
            [self.titleMarr replaceObjectAtIndex:tableView.tag withObject:countyModel.name];
            //1. 修改选中ID
            if (self.titleIDMarr.count > 2){
                [self.titleIDMarr replaceObjectAtIndex:tableView.tag withObject:countyID];
            } else{
                [self.titleIDMarr addObject:countyID];
            }
            //2.修改标题
            [self.titleMarr replaceObjectAtIndex:tableView.tag withObject:countyModel.name];
            
#pragma mark  修改展示到区级  不往下继续展示
            //网络请求，添加县城
//            [self getAddressMessageDataAddressID:4 parentCode:countyID];
//            if (self.tableViewMarr.count >= 3){
//               [self changeTitle:2];
//            } else{
//                [self addTableViewAndTitle:2];
//            }
            [self setupAllTitle:tableView.tag];
            if (self.isChangeAddress == false){
                [self tapBtnAndcancelBtnClick];
            } else{
                self.isChangeAddress = false;
            }
        }
    } else if (tableView.tag == 3) {
        DLAddressModel * townModel = self.townMarr[indexPath.row];
        NSString * townID = townModel.code;
        [self.titleMarr replaceObjectAtIndex:tableView.tag withObject:townModel.name];
        //1. 修改选中ID
        if (self.titleIDMarr.count > 3){
            [self.titleIDMarr replaceObjectAtIndex:tableView.tag withObject:townID];
        } else{
            [self.titleIDMarr addObject:townID];
        }
        [self setupAllTitle:tableView.tag];
        if (self.isChangeAddress == false){
            [self tapBtnAndcancelBtnClick];
        } else{
            self.isChangeAddress = false;
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  40;
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass(touch.view.classForCoder) isEqualToString: @"UITableViewCellContentView"] || touch.view == self.addAddressView || touch.view == self.titleScrollView) {
        return NO;
    }
    return YES;
}
//添加tableView和title
-(void)addTableViewAndTitle:(NSInteger)tableViewTag{
    UITableView * tableView2 = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 200) style:UITableViewStylePlain];
    tableView2.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView2 registerClass:[HNSH_AgentAddressViewCell class] forCellReuseIdentifier:HNSH_AgentAddressViewCellID];
    tableView2.tag = tableViewTag;
    [self.tableViewMarr addObject:tableView2];
    [self.titleMarr addObject:@"请选择"];
}
//改变title
-(void)changeTitle:(NSInteger)replaceTitleMarrIndex{
    [self.titleMarr replaceObjectAtIndex:replaceTitleMarrIndex withObject:@"请选择"];
    NSInteger index = [self.titleMarr indexOfObject:@"请选择"];
    NSInteger count = self.titleMarr.count;
    NSInteger loc = index + 1;
    NSInteger range = count - index;
    [self.titleMarr removeObjectsInRange:NSMakeRange(loc, range - 1)];
    [self.tableViewMarr removeObjectsInRange:NSMakeRange(loc, range - 1)];
}

//(以下注释部分是网络请求)
-(void)getAddressMessageDataAddressID:(NSInteger)com  parentCode:(NSString *)parentCode{
    NSDictionary * params = @{@"parentCode":parentCode};
    [HNSH_ShopNetServer requestRegionListWithParams:params success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSArray * array = [NSArray yy_modelArrayWithClass:DLAddressModel.class json:responseObject.resultset];
            if (com == 1) {
                self.provinceMarr = array;
            } else if (com == 2) {
                self.cityMarr = array;
                if (self.tableViewMarr.count >= 2){
                    [self changeTitle:1];
                } else{
                    [self addTableViewAndTitle:1];
                }
                [self setupAllTitle:1];
            } else if (com == 3) {
                self.countyMarr = array;
                if (self.tableViewMarr.count >= 3){
                   [self changeTitle:2];
                } else{
                    [self addTableViewAndTitle:2];
                }
                [self setupAllTitle:2];
            } else if (com == 4) {
                self.townMarr = array;
                if (self.tableViewMarr.count >= 4){
                   [self changeTitle:3];
                } else{
                    [self addTableViewAndTitle:3];
                }
                [self setupAllTitle:3];
            }
            if (self.tableViewMarr.count >= com){
                UITableView * tableView1  = self.tableViewMarr[com - 1];
                [tableView1 reloadData];
            }
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
      
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
